package com.honvay.cola.auth.base.component;

import com.honvay.cola.auth.core.model.AuthenticatedUser;
import com.honvay.cola.uc.api.UserService;
import com.honvay.cola.uc.api.enums.UserLockStatus;
import com.honvay.cola.uc.api.enums.UserStatus;
import com.honvay.cola.uc.api.model.UserDto;

import java.time.LocalDateTime;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

/**
 * @author LIQIU
 * @date 21.5.18
 */
@Component
public class UserDetailsServiceImpl implements UserDetailsService {

	@Autowired
	private UserService userService;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

		UserDto user = userService.findByUsername(username);
		if (user == null) {
			throw new UsernameNotFoundException("User " + username + " can not be found");
		}

		return buildAuthenticatedUser(user);
	}

	private AuthenticatedUser buildAuthenticatedUser(UserDto user) {
		AuthenticatedUser authenticatedUser = new AuthenticatedUser();
		authenticatedUser.setId(user.getId());
		authenticatedUser.setUsername(user.getUsername());
		authenticatedUser.setPassword(user.getPassword());
		authenticatedUser.setPhoneNumber(user.getPhoneNumber());
		authenticatedUser.setEmail(user.getEmail());
		authenticatedUser.setAvatar(user.getAvatar());
		authenticatedUser.setLocked(UserLockStatus.LOCKED.getValue().equals(user.getLocked()));
		authenticatedUser.setEnable(UserStatus.ACTIVE.getValue().equals(user.getStatus()));
		authenticatedUser.setAuthorities(user.getAuthorities());
		
		// 账号过期
		if (null != user.getAccountExpiredTime() && LocalDateTime.now().isAfter(user.getAccountExpiredTime())) {
			authenticatedUser.setAccountNonExpired(false);
		}
		
		// 凭证过期、密码过期
		if (null != user.getCredentialsExpiredTime() && LocalDateTime.now().isAfter(user.getCredentialsExpiredTime())) {
			authenticatedUser.setCredentialsNonExpired(false);
		}
		return authenticatedUser;
	}
}
